<?php

namespace AppBundle\Controller;

use AdminBundle\Entity\HuobiCalcKline1min;
use AdminBundle\Entity\HuobiMarketKline1min;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

class HuobiKLine1minController extends HuobiKlineBaseController
{
    const CACHE_KLINE_KEY = 'list:kline_1min';

    /**
     * 接收WEBSOCKET同步过来的火币K线图（1分钟）数据
     * @Route("/kline1min", name="huobi_market_kline_1min")
     */
    public function indexAction(Request $request)
    {
        return parent::receiveKline($request);
    }

    protected function KlineInstance($data_now, $prefix)
    {
        $huobiMarketKline1min = new HuobiMarketKline1min($data_now, $prefix);
        return $huobiMarketKline1min;
    }

    protected function getKline($coin, $timestamp = 0, $duration = 60)
    {
        $em = $this->getDoctrine()->getManager();
        $data = $em->getRepository('AdminBundle:HuobiMarketKline1min')->get60mins($coin, $timestamp, $duration);
        return $data;
    }

    protected function KlineCalcInstance($data)
    {
        $HuobiCalcKline1min = new HuobiCalcKline1min($data);
        return $HuobiCalcKline1min;

    }

    protected function cacheKey()
    {
        return self::CACHE_KLINE_KEY;
    }

    protected function klinePeriod()
    {
        $kline_multiple = [
            "3" => 3, "5" => 5, "7" => 7, "10" => 10, "15" => 15, "20" => 20, "30" => 30,
            "60" => 60, "120" => 120, "180" => 180, "240" => 240];

        return $kline_multiple;
    }

    /**
     * 接收WEBSOCKET同步过来的火币K线图（1分钟）数据
     * @Route("/pricealert", name="huobi_market_kline_1min_price_alert")
     */
    public function priceAlertAction(Request $request, $call_src = 'request')
    {
        $content = $request->getContent();
        $data = json_decode($content, true);

        if ($data == null || !isset($data['ch']) || !isset($data['tick'])) {
            return $this->apiResult(1, 'empty data.', $content);
        }
// -------------------------------------------------------------------------------
//        $data = $data ?: [];
//        $data_default = ["ch" => 'market.btcusdt.kline.1min', "ts" => time(),
//            "tick" => ["id" => time(), "open" => 0, "close" => 0, "low" => 0,
//                "high" => 0, "amount" => 0, "vol" => 0, "count" => 0]
//        ];
//        $data = array_replace_recursive($data_default, $data);
// -------------------------------------------------------------------------------

        $coin = explode('.', $data['ch'])[1];
        $tick = $data['tick'];

        $em = $this->getDoctrine()->getManager();
        $huobiAlertPrices = $em->getRepository('AdminBundle:HuobiAlertPrice')->findBy(['coin' => $coin, 'status' => 0]);

        $flag = false;
        if ($huobiAlertPrices) {
            foreach ($huobiAlertPrices as $huobiAlertPrice) {
                if ($huobiAlertPrice->getDirect() == 'up') {
                    if ($tick['close'] > $huobiAlertPrice->getPrice() || $tick['high'] > $huobiAlertPrice->getPrice()) {
                        $flag = true;
                    }
                } else {
                    if ($tick['close'] < $huobiAlertPrice->getPrice() || $tick['low'] < $huobiAlertPrice->getPrice()) {
                        $flag = true;
                    }
                }
            }
        }

        if ($flag && $call_src === 'function') {
            $response = $this->render('HuobiKLine1min/mail.html.twig', [
                'title' => '价格警报通知',
                'tick' => $tick,
                'data' => $data,
            ]);
            // 发送邮件
            $result = $this->sendMail('RISING OR FALLING', $response->getContent(), ['recipient' => 'master']);

            return $tick;
        }
        return $this->apiResult(0, '', $flag);
    }


}
